# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Generates a header file configuring the default retry policy parameters from the GAPIC YAML config files.

GAPIC defines default values for the retry policies in the client library.

For Bigtable admin APIs it is defined in bigtableadmin_gapic.yaml
https://raw.githubusercontent.com/googleapis/googleapis/master/google/bigtable/admin/v2/bigtableadmin_gapic.yaml

For Bigtable data APIs it is defined in bigtable_gapic.yaml
https://raw.githubusercontent.com/googleapis/googleapis/master/google/bigtable/v2/bigtable_gapic.yaml

This script reads both YAML files and generates a C++ header file that define
constants which is used in retry and backoff policies for Cloud Bigtable C++ Client Library.

Usage:

    python ../tools/generate_rpc_policy_parameters.py \
    | clang-format > rpc_policy_parameters.inc
"""

from __future__ import print_function

import collections
import yaml
import urllib

FILE_HEADER = """
// AUTOGENERATED BY tools/generate_rpc_policy_parameters.py; DO NOT EDIT MANUALLY.
// ALL MANUAL CHANGES WILL BE OVERWRITTEN.
//
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
"""


def print_defines(interface):
    defines = []
    prefix = "GOOGLE_CLOUD_CPP_" + interface["name"].upper().rsplit(".", 1)[1]
    struct = interface["name"].rsplit(".", 1)[1]
    constants = collections.OrderedDict()
    constants["_DEFAULT_INITIAL_DELAY"] = "initial_retry_delay_millis"
    constants["_DEFAULT_MAXIMUM_DELAY"] = "max_retry_delay_millis"
    constants["_DEFAULT_MAXIMUM_RETRY_PERIOD"] = "total_timeout_millis"

    print("// Define the defaults using a pre-processor macro, this allows")
    print("// the application developers to change the defaults for their")
    print("// application by compiling with different values.")
    print("")
    for constant in constants:
        name = prefix + constant
        val = interface["retry_params_def"][0]
        o = "#define " + name
        o += " std::chrono::milliseconds(" + str(val[constants[constant]])
        o += ")"

        print("#ifndef " + name)
        print(o)
        print("#endif //" + name)
        print("")

        defines.append(name)
    print("")
    print("RPCPolicyParameters const k" + struct + "Limits = {")
    for constant in constants:
        print(prefix + constant + ",")
    print("};")
    return defines


def main():
    all_defines = []
    links = [
        "https://raw.githubusercontent.com/googleapis/googleapis/master/google/bigtable/admin/v2/bigtableadmin_gapic.yaml",
        "https://raw.githubusercontent.com/googleapis/googleapis/master/google/bigtable/v2/bigtable_gapic.yaml",
    ]

    print(FILE_HEADER.lstrip())

    for link in links:
        f = urllib.urlopen(link)
        myfile = f.read()
        t = yaml.load(myfile)
        for intf in t["interfaces"]:
            print("")
            print('// Interface name: "' + intf["name"] + '"')
            intf_defines = print_defines(intf)
            all_defines.append(intf_defines)
            print("")

    flat_list = [item for sublist in all_defines for item in sublist]

    for define in flat_list:
        print("#undef " + define)


if __name__ == "__main__":
    main()
